package com.aegis.gateway.service;

import com.aegis.gateway.model.AppInfo;
import com.aegis.gateway.service.cache.CacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * @Author wuweixin
 *
 * @Version 1.0
 * @Descritube
 */
@Slf4j
@Component
public class InitService {

    @Autowired
    private CacheService<AppInfo> cacheService;

    @EventListener(ApplicationReadyEvent.class)
    public void onReady() {
        new Thread(() -> {
            log.info("开始初始化数据");
            boolean available = false;
            int retry = 0;
            while (!available && retry < 30) {
                try {
                    cacheService.syncCache(); // 尝试 RPC
                    available = true;
                    log.info("✅ Dubbo RPC 成功，服务已就绪");
                } catch (Exception e) {
                    retry++;
                    log.info("⏳ Dubbo 还未 ready，重试中: " + retry);
                    try {
                        Thread.sleep(1000); // 每秒重试一次
                    } catch (InterruptedException ignored) {}
                }
            }

            if (!available) {
                log.info("❌ Dubbo 仍不可用，请检查 Provider 是否注册");
            }
        }).start();
    }

}